package com.kc.data.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Collectors;

public class JsonUtils<T> {
    /**
     * object 转 string
     * @param object
     * @return
     */
    public static String toJson(Object object){
        Gson gson = new Gson();
        return gson.toJson(object);
    }

    /**
     * json穿转换成对象
     * @param json
     * @param listType
     * @param <T>
     * @return
     */
    public static  <T> T fromToJson(String json, Type listType){
        Gson gson = new Gson();
        T t = null;
        t = gson.fromJson(json,listType);
        return t;
    }

    /**
     * json字符串转string list
     * @param str
     * @return
     */
    public static List<String> jsonStringToListString(String str){
        List<Object> strObject = JSONArray.parseArray(str);
        List<String> strList = strObject.stream().map(e->e.toString()).collect(Collectors.toList());
        return strList;
    }

    public static String bean2Json(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
